﻿/**************************************************************
 * Project     : Titan Framework
 * Copyright (C) 2011 Microsoft Corp.
 * Author      : Julian Hu
 * Mail        : junhu@microsoft.com
 * Create Date : 2011-05-10
 * Summary     :   
 * 
 * 
 * Modified By : 
 * Date        : 
 * Mail        : 
 * Comment     :   
 * *************************************************************/

using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;

namespace Titan.Logging
{
    /// <summary>
    /// 扩展IDisposable,处理资源的释放.
    /// </summary>
    public abstract class DisposableObject : IDisposable
    {
        #region Properties

        public bool IsDisposed { get; private set; }
        #endregion

        #region Disposal

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool disposing)
        {
            IsDisposed = true;
        }

        ~DisposableObject()
        {
            Dispose(false);
        }
        #endregion

        #region Protected Methods

        protected static void DisposeMember(object member)
        {
            IDisposable disposable = member as IDisposable;

            if (disposable != null)
                disposable.Dispose();
        }

        protected static void DisposeCollection(IEnumerable collection)
        {
            if (collection != null)
            {
                foreach (object obj in collection)
                    DisposeMember(obj);

                DisposeMember(collection);
            }
        }

        protected static void DisposeDictionary<K, V>(IDictionary<K, V> dictionary)
        {
            if (dictionary != null)
            {
                foreach (KeyValuePair<K, V> entry in dictionary)
                    DisposeMember(entry.Value);

                DisposeMember(dictionary);
            }
        }
        #endregion
    }
}
